using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HealthBarUI : MonoBehaviour
{
    public bool alwaysVisable;
    public float visableTime;
    private float visableTimeCounter;
    public GameObject healhBarPrefab;
    public Transform barPoint;
    private Image healthSlider;
    // 实例化后显示位置
    private Transform UIBar;
    private Transform cam;

    private CharacterStats characterStats;
    private void Awake()
    {
        characterStats = GetComponent<CharacterStats>();
        cam = Camera.main.transform;
    }
    private void OnEnable()
    {

        characterStats.UpdateHealthBarOnAttack += UpdateHealthBar;
        foreach (Canvas canvas in FindObjectsOfType<Canvas>())
        {
            // 只有血条的 canvas 是世界渲染，所以才能这样做
            if (canvas.renderMode == RenderMode.WorldSpace)
            {
                UIBar = Instantiate(healhBarPrefab, canvas.transform).transform;
                healthSlider = UIBar.GetChild(0).GetComponent<Image>();

                UIBar.gameObject.SetActive(alwaysVisable);
            }
        }
    }
    private void OnDisable()
    {
        characterStats.UpdateHealthBarOnAttack -= UpdateHealthBar;
    }

    private void UpdateHealthBar(int currentHealth, int maxHealth)
    {
        if (UIBar==null)
        {
            return;
        }
        if (currentHealth <= 0)
        {
            Destroy(UIBar.gameObject);
        }
        UIBar.gameObject.SetActive(true);
        visableTimeCounter = visableTime;

        float sliderPercent = (float)currentHealth / maxHealth;

        healthSlider.fillAmount = sliderPercent;
    }
    private void LateUpdate()
    {
        if (UIBar != null)
        {
            UIBar.position = barPoint.position;
            // 血条始终处于摄像机的反向
            UIBar.forward = -cam.forward;

            if (visableTimeCounter <= 0 && !alwaysVisable)
            {
                UIBar.gameObject.SetActive(false);
            }
            else
            {
                visableTimeCounter -= Time.deltaTime;
            }
        }
    }
}
